<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef">
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="指标内容:" prop="content">
            <el-input
              v-model="queryForm.content"
              placeholder="指标内容"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="7">
          <!--    被考核人      -->
          <el-form-item label="被考核人:" prop="appraisee">
            <el-input
              @focus="selectAppraiserUser"
              v-model="queryForm.appraisee"
              placeholder="被考核人"
            >
              <template #prepend v-if="appraiserUserObj.length > 0">
                {{ appraiserUserObj[0].label }}
              </template>
              <template #append>
                <el-button
                  type="primary"
                  size="small"
                  @click="selectAppraiserUser"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <!--    考核人    -->
        <el-col :span="7">
          <el-form-item label="考核人:" prop="assessor">
            <el-input
              v-model="queryForm.assessor"
              placeholder="考核人"
              @focus="selectAssessorUser"
            >
              <template #prepend v-if="assessorUserObj.length > 0">
                {{ assessorUserObj[0].label }}
              </template>
              <template #append>
                <el-button
                  type="primary"
                  size="small"
                  @click="selectAssessorUser"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="mb-2">
      <el-button type="primary" icon="Plus" @click="dialogVisible = true"
        >指标录入</el-button
      >
      <el-button type="primary" plain icon="Edit" @click="handleUpdate"
        >编辑指标</el-button
      >
      <el-button type="primary" plain icon="Delete" @click="deleteIndicator"
        >删除指标</el-button
      >
      <el-button type="primary" plain icon="Download" @click="handleDownLoad"
        >导出指标</el-button
      >
    </div>
    <div>
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          fixed
          width="55"
        ></el-table-column>
        <el-table-column
          label="一级指标"
          fixed
          width="150"
          show-overflow-tooltip
          prop="firstLevel"
        ></el-table-column>
        <el-table-column
          label="二级指标"
          fixed
          width="150"
          show-overflow-tooltip
          prop="secondLevel"
        ></el-table-column>
        <el-table-column
          label="指标说明及工作内容、工作要求等"
          fixed
          width="300"
          show-overflow-tooltip
          prop="content"
        ></el-table-column>
        <el-table-column label="指标单位" width="100" prop="unit">
          <!--          <template #default="scope">-->
          <!--            <dict-tag :options="indicator_unit" :value="scope.row.unit" />-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column
          label="指标值"
          width="100"
          prop="targetValue"
        ></el-table-column>
        <el-table-column
          label="考核评分标准"
          prop="scoreStandard"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column
          label="分值权重"
          width="120"
          prop="score"
        ></el-table-column>
        <el-table-column
          label="考核人姓名"
          width="120"
          show-overflow-tooltip
          prop="assessorUserName"
        ></el-table-column>
        <el-table-column
          label="考核人部门"
          width="120"
          show-overflow-tooltip
          prop="assessorDeptName"
        ></el-table-column>
        <el-table-column
          label="考核人职务"
          show-overflow-tooltip
          width="120"
          prop="assessorDutiesName"
        ></el-table-column>
        <el-table-column
          label="考核人岗位"
          show-overflow-tooltip
          width="120"
          prop="assessorPostName"
        ></el-table-column>
        <el-table-column
          label="被考核人部门"
          prop="appraiseeDeptName"
          show-overflow-tooltip
          width="120"
        ></el-table-column>
        <el-table-column
          width="120"
          label="被考核人姓名"
          show-overflow-tooltip
          prop="appraiseeUserName"
        ></el-table-column>
        <el-table-column
          width="120"
          label="被考核人岗位"
          show-overflow-tooltip
          prop="appraiseePostName"
        ></el-table-column>
        <el-table-column
          width="120"
          label="被考核人职务"
          show-overflow-tooltip
          prop="appraiseeDutiesName"
        ></el-table-column>
        <el-table-column width="120" label="考核频率" prop="frequency">
          <template #default="scope">
            <dict-tag
              :options="examine_frequency"
              :value="scope.row.frequency"
            />
          </template>
        </el-table-column>
        <el-table-column width="120" label="计分方式" prop="scoreMethod">
          <template #default="scope">
            <dict-tag
              :options="scoring_method"
              :value="scope.row.scoreMethod"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
    </div>

    <!--  弹窗选择组件  -->
    <select-or-tree-dialog
      :dialog-param="selectOrTreeDialogParam"
      :tabsOptionsData="tabsOptionsData"
      @handleConfirm="handleConfirm"
    />
    <el-dialog
      :width="dialogWidth"
      v-model="dialogVisible"
      @close="dialogClose"
      destroy-on-close
      class="indicatorDialog"
      :style="
        flag == 'add'
          ? 'margin-top: 6vh !important'
          : 'margin-top: 20vh !important'
      "
    >
      <template #title>
        <div class="text-2xl pl-5 font-semibold">考核指标</div>
      </template>
      <el-row v-if="flag == ''" class="px-20">
        <el-col :span="24">
          <el-button
            icon="Upload"
            class="indicatorDialogBtn w-full mb-5 mt-5 h-10"
            style="color: #409eff"
            @click="uploadIndicator"
            >上传指标</el-button
          >
        </el-col>
        <el-col :span="24">
          <el-button
            icon="Plus"
            class="indicatorDialogBtn w-full h-10 mb-10"
            style="color: #409eff"
            @click="addIndicator"
            >指标录入</el-button
          >
        </el-col>
      </el-row>
      <add-or-update-indicator
        @dialogClose="dialogClose"
        v-if="flag == 'add'"
        :indicatorInfo="indicatorInfo"
      />
      <UploadIndicator @dialogClose="dialogClose" v-if="flag == 'upload'" />
    </el-dialog>
  </div>
</template>
<!-- 指标管理 -->
<script setup name="IndicatorManage">
import { getCurrentInstance } from 'vue'
import { listDept } from '@/api/system/dept'
import { listPost } from '@/api/system/post'
import {
  deleteBizofficeconf,
  getBizofficeconfList,
  saveBizofficeconfInfo
} from '@/api/officeManage/indicator'
import useCommonStore from '@/store/modules/common'
import AddOrUpdateIndicator from '@/views/officeManage/performanceManage/indicatorManage/modules/addOrUpdateIndicator'
import UploadIndicator from '@/views/officeManage/performanceManage/indicatorManage/modules/uploadIndicator'
// 通用数据store
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()

const data = reactive({
  queryForm: {
    pageSize: 10,
    pageNum: 1
  },
  total: 0,

  deptProps: { label: 'deptName' },
  selectOptionObj: {}, // select
  selectOrTreeDialogParam: {},
  tableData: [],
  flag: '',
  dialogWidth: '40%',
  confirmType: '',
  tabsOptionsData: [],
  selectionData: [],
  loading: false,
  indicatorInfo: ''
})
const {
  queryForm,
  total,
  tabsOptionsData,
  deptProps,
  confirmType,
  selectOrTreeDialogParam,
  selectionData,
  selectOptionObj,
  tableData,
  flag,
  dialogWidth,
  loading,
  indicatorInfo
} = toRefs(data)

const { scoring_method, indicator_unit, examine_frequency } = proxy.useDict(
  'scoring_method',
  'indicator_unit',
  'examine_frequency'
)
// 弹窗开关
const dialogVisible = ref(false)
// 考核人对象数组
const assessorUserObj = ref([])
// 被考核人对象数组
const appraiserUserObj = ref([])

/**
 * 导出指标
 */
const handleDownLoad = () => {
  let params = JSON.parse(JSON.stringify(queryForm.value))
  console.info(appraiserUserObj.value)
  if (appraiserUserObj.value.length > 0) {
    let obj = appraiserUserObj.value[0]
    switch (obj.name) {
      case 'dept':
        params.appraiseeDept = obj.selectData[0].itemValue
        break
      case 'duties':
        params.appraiseeDuties = obj.selectData[0].itemValue
        break
      case 'post':
        params.appraiseePost = obj.selectData[0].itemValue
        break
      case 'person':
        params.appraiseeUser = obj.selectData[0].itemValue
        break
    }
  }
  if (assessorUserObj.value.length > 0) {
    let obj = assessorUserObj.value[0]
    switch (obj.name) {
      case 'dept':
        params.assessorDept = obj.selectData[0].itemValue
        break
      case 'duties':
        params.assessorDuties = obj.selectData[0].itemValue
        break
      case 'post':
        params.assessorPost = obj.selectData[0].itemValue
        break
      case 'person':
        params.assessorUser = obj.selectData[0].itemValue
        break
    }
  }
  delete params.assessor
  delete params.appraisee
  proxy.downLoadByUrl(
    '/office/bizofficeconf/outPutExcel',
    params,
    '考核指标.xlsx'
  )
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
  console.info('selectionData', selectionData)
}

/**
 * 编辑指标
 */
const handleUpdate = () => {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionData.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }
  indicatorInfo.value = selectionData.value[0]

  addIndicator()
  dialogVisible.value = true
}

/**
 * 删除指标
 */
const deleteIndicator = () => {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的数据-？')
    .then(res => {
      let ids = selectionData.value.map(item => item.id).join(',')

      deleteBizofficeconf({ ids }).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
    .catch(() => {})
}

/**
 * dialogClose 关闭弹窗，并且设置flag为false
 */
const dialogClose = () => {
  dialogVisible.value = false
  indicatorInfo.value = ''
  proxy.$nextTick(() => {
    flag.value = ''
    dialogWidth.value = '40%'
    getList()
  })
}

/**
 * 添加指标
 */
const addIndicator = () => {
  flag.value = 'add'
  dialogWidth.value = '85%'
}

/**
 * 上传指标
 */
const uploadIndicator = () => {
  flag.value = 'upload'
  dialogWidth.value = '40%'
}

/**
 * getList 查询方法
 */
const getList = () => {
  loading.value = true
  let params = JSON.parse(JSON.stringify(queryForm.value))
  console.info(appraiserUserObj.value)
  if (appraiserUserObj.value.length > 0) {
    let obj = appraiserUserObj.value[0]
    switch (obj.name) {
      case 'dept':
        params.appraiseeDept = obj.selectData[0].itemValue
        break
      case 'duties':
        params.appraiseeDuties = obj.selectData[0].itemLabel
        break
      case 'post':
        params.appraiseePost = obj.selectData[0].itemLabel
        break
      case 'person':
        params.appraiseeUser = obj.selectData[0].itemValue
        break
    }
  }
  if (assessorUserObj.value.length > 0) {
    let obj = assessorUserObj.value[0]
    switch (obj.name) {
      case 'dept':
        params.assessorDept = obj.selectData[0].itemValue
        break
      case 'duties':
        params.assessorDuties = obj.selectData[0].itemLabel
        break
      case 'post':
        params.assessorPost = obj.selectData[0].itemLabel
        break
      case 'person':
        params.assessorUser = obj.selectData[0].itemValue
        break
    }
  }
  delete params.assessor
  delete params.appraisee
  getBizofficeconfList(params)
    .then(res => {
      total.value = res.data.total
      tableData.value = res.data.records
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * ref queryForm的重置方法 重置表单
 *
 */
const resetForm = () => {
  assessorUserObj.value = []
  // 设置被考核人对象数组
  appraiserUserObj.value = []
  proxy.$refs['queryFormRef'].resetFields()
  getList()
}

/**
 * @description: 选择考核人
 */
const selectAssessorUser = () => {
  // 设置confirmType显示提交类型
  confirmType.value = 'assessorUser'
  //   tabs配置数组
  tabsOptionsData.value = [
    {
      label: '组织架构', //tab的label
      name: 'dept', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'dept', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName' //树节点的label
      }
    },
    {
      label: '人员列表', //tab的label
      name: 'person', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'person', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'uuid', //节点的key
        defaultCheckedKeys: [] //默认选中的节点
      }
    },
    {
      label: '岗位', //tab的label
      name: 'post', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'post', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'postId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'postName' //树节点的label
      }
    },
    {
      label: '职务', //tab的label
      name: 'duties', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'duties', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'value', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'label' //树节点的label
      }
    }
  ]
  // 如果考核人对象数组有值
  if (assessorUserObj.value.length > 0) {
    //assessorUserObj,用find查找tabsOptionsData中name等于assessorUserObj的name的对象
    //将对象的componentOptions.defaultCheckedKeys设置为考核人对象数组中的selectData的itemValue集合
    //componentOptions的selectData等于assessorUserObj中的selectData
    assessorUserObj.value.forEach(item => {
      const obj = tabsOptionsData.value.find(tab => tab.name === item.name)
      obj.componentOptions.defaultCheckedKeys = item.selectData.map(
        item => item.itemValue
      )
      obj.componentOptions.selectData = item.selectData
    })
  }

  proxy.$nextTick(() => {
    // 弹窗标题
    selectOrTreeDialogParam.value.title = '考核人'
    // 弹窗是否发开
    selectOrTreeDialogParam.value.isDialog = true
    //  是否多选，如果结果要为单选，则组件componentOptions.multiple设置为false
    selectOrTreeDialogParam.value.resultMultiple = false
  })
}

/**
 * @description: 选择被考核人
 */
const selectAppraiserUser = () => {
  // 设置confirmType显示提交类型
  confirmType.value = 'appraiserUser'
  //   tabs配置数组
  tabsOptionsData.value = [
    {
      label: '部门', //tab的label
      name: 'dept', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'dept', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName' //树节点的label
      }
    },
    {
      label: '人员', //tab的label
      name: 'person', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'person', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'uuid', //节点的key
        defaultCheckedKeys: [] //默认选中的节点
      }
    },
    {
      label: '岗位', //tab的label
      name: 'post', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'post', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'postId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'postName' //树节点的label
      }
    },
    {
      label: '职务', //tab的label
      name: 'duties', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'duties', //数据类型
        multiple: false, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'value', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'label' //树节点的label
      }
    }
  ]
  // 如果考核人对象数组有值
  if (appraiserUserObj.value.length > 0) {
    //遍历appraiserUserObj,用find查找tabsOptionsData中name等于appraiserUserObj的name的对象
    //将对象的componentOptions.defaultCheckedKeys设置为考核人对象数组中的selectData的itemValue集合
    //componentOptions的selectData等于appraiserUserObj中的selectData
    appraiserUserObj.value.forEach(item => {
      const obj = tabsOptionsData.value.find(tab => tab.name === item.name)
      obj.componentOptions.defaultCheckedKeys = item.selectData.map(
        item => item.itemValue
      )
      obj.componentOptions.selectData = item.selectData
    })
  }

  proxy.$nextTick(() => {
    // 弹窗标题
    selectOrTreeDialogParam.value.title = '被考核人'
    // 弹窗是否发开
    selectOrTreeDialogParam.value.isDialog = true
    //  是否多选
    selectOrTreeDialogParam.value.resultMultiple = false
  })
}

/**
 * 考核人弹窗确定按钮
 */
const handleConfirm = result => {
  console.info('result', result)
  if (result.length > 0) {
    // 如果confirmType为assessorUser
    if (confirmType.value === 'assessorUser') {
      queryForm.value.assessor = result[0].selectData[0].itemLabel
      // 设置考核人对象数组
      assessorUserObj.value = result
    } else {
      queryForm.value.appraisee = result[0].selectData[0].itemLabel
      // 设置被考核人对象数组
      appraiserUserObj.value = result
    }
  } else {
    // 如果confirmType为assessorUser
    if (confirmType.value === 'assessorUser') {
      queryForm.value.assessor = ''
      // 设置考核人对象数组
      assessorUserObj.value = []
    } else {
      queryForm.value.appraisee = ''
      // 设置被考核人对象数组
      appraiserUserObj.value = []
    }
  }
}

/**
 * 初始化
 */
const init = () => {
  getList()
}

init()
</script>
<style lang="scss" scoped>
:deep(.indicatorDialog) {
  border-radius: 10px;
  .el-dialog__body {
    padding: 0;
  }
  .indicatorDialogBtn {
    padding: 20px 0 !important;
    font-weight: bold !important;
    border-width: 2px !important;
  }
  .el-dialog__header {
    @apply py-5 mr-0 border-b-1 border-b-solid border-gray-200;
  }
  .el-dialog__headerbtn {
    top: 0;
  }
}
</style>
